package com.itheima.transaction;

import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 我的事务管理器
 */
/*@Component*/
public class MyTransactionManager {
private DataSource dataSource;

    public MyTransactionManager(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public MyTransactionManager() {

    }

    public Connection start() throws Exception {
     System.out.println("开启事务");
     Connection connection = dataSource.getConnection();
     //负责开启事务
     connection.setAutoCommit(false);
     return connection;
 }
    public void commit(Connection connection) throws Exception {
        System.out.println("使用事务管理提交事务");

        //负责提交事务
        connection.commit();

    }


    public void rollback(Connection connection){
        System.out.println("回滚事务");
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void close(Connection connection){
        System.out.println("关闭资源");
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
